/*
 * Copyright 2011 Dominik Pretzsch <dominik.pretzsch at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.blacksheep.jmoteextract.extraction;

import de.blacksheep.jmoteextract.thread.ThreadDispatcher;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * <code>ExtractionQueueManager</code> provides functionality for <br>
 * automated extraction of archives. It handles the <br>
 * {@see ExtractionQueue} and holds a {@see ThreadDispatcher} <br>
 * to distribute the {@see ExtractionCallable}s to a <br>
 * thread pool.
 * 
 * @author Dominik Pretzsch <dominik.pretzsch at gmail.com>
 * @see ExtractionQueue
 * @see ThreadDispatcher
 * @see ExtractionCallable
 */
public class ExtractionQueueManager extends Thread {
    
    private ExtractionQueue QUEUE;    
    private ThreadDispatcher DISPATCHER;
    
    private static final Logger LOGGER =  Logger.getLogger(ExtractionQueueManager.class.getName());
    
    public ExtractionQueueManager(ThreadDispatcher dispatcher) {
        this.QUEUE = ExtractionQueue.getInstance();
        this.DISPATCHER = dispatcher;
        
        this.setName(this.getClass().getName());
        this.setDaemon(true);
    }

    @Override
    public void run() {        
        // TODO: shutdown thread pool. Delete uncomplete extractions
        // TODO: Observer
        // Busy wait, I know... :-/
        while (true) {
            if (!DISPATCHER.isBusy()) {
                LOGGER.log(Level.FINE, "Dispatcher available. Try to dequeue EC...");                
                ExtractionCallable ec = QUEUE.dequeue();
                LOGGER.log(Level.FINE, "... EC dequeued. Try to submit...");
                int result = DISPATCHER.submit(ec);
                if (result == 0) {                     
                    LOGGER.log(Level.FINE, "... Dispatcher went busy. Requeue..."); 
                    QUEUE.enqueue(ec);
                } else {
                    LOGGER.log(Level.FINE, "... Submitted."); 
                }
            } else {
                synchronized (this) {
                    try {
                        wait(0, 10000);
                    } catch (InterruptedException ex) {
                        // TODO: InterruptedException
                        LOGGER.log(Level.SEVERE, "IOException", ex);
                    }
                }
            }
        }
    }
}
